package com.crb.crm.manage.oos.upyun;

import com.crb.crm.manage.enums.OssType;
import com.crb.crm.manage.oos.OSSUtil;
import com.upyun.RestManager;
import com.upyun.UpException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * 又拍云上传下载工具类【在报错】
 **/
@Slf4j
@Component
class UpyunUtil implements OSSUtil {

    @Resource
    private UpyunConfig upyunConfig;

    private RestManager getRestManager() {
        return new RestManager(upyunConfig.getBucketName(), upyunConfig.getOperatorName(), upyunConfig.getOperatorPwd());
    }

    @Override
    public OssType support() {
        return OssType.OSS_UPYUN;
    }

    @Override
    public boolean upload(InputStream is, String key) {
        RestManager client = getRestManager();
        try {
            Response response = client.writeFile(key, is, null);
            return response.isSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean delete(String key) {
        RestManager client = getRestManager();
        try {

            Response response = client.deleteFile(key, null);
            return response.isSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public InputStream download(String key) {
        RestManager client = getRestManager();
        Response  response;
        try {
            response = client.getFileInfo(key);
            if (response.isSuccessful()) {
                return response.body().byteStream();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UpException e) {
            e.printStackTrace();
        }
        return null;
    }
}